﻿using Jay.Sc2.Bof.Lib.State;

namespace Jay.Sc2.Bof.Lib.Action.Terran
{
	public abstract class ActionProduceFromSCV : ActionProduceTerran
	{
		public ActionProduceFromSCV(int buildTime, int minerals, int gas) : base(buildTime, minerals, gas, 0) { }

		public override int AvailableProducer(IBuildOrder bo)
		{
			TerranState state = bo.State as TerranState;
			return state.WorkersOnMinerals + state.WorkersOnGas;
		}

		public abstract TerranState.TerranBuilding GetBuilding(TerranState state);
		public abstract string EventName { get; }

		public override void Execute(IBuildOrder bo)
		{
			TerranState state = bo.State as TerranState;
			if (state.WorkersOnMinerals > 0)
			{
				state.WorkersOnMinerals--;
				base.Execute(bo);
				OnProductionStart(bo);
				bo.AddAction(state.Time + BuildTime, new ActionGeneric(EventName, delegate(IBuildOrder ibo)
				{
					state.WorkersOnMinerals++;
					OnProductionFinished(ibo);
				}));
			}
			else if (state.WorkersOnGas > 0)
			{
				state.WorkersOnGas--;
				base.Execute(bo);
				OnProductionStart(bo);
				bo.AddAction(state.Time + BuildTime, new ActionGeneric(EventName, delegate(IBuildOrder ibo)
				{
					state.WorkersOnGas++;
					OnProductionFinished(ibo);
				}));
			}
			else throw new InvalidActionException();
		}

		public virtual void OnProductionFinished(IBuildOrder bo)
		{
			TerranState.TerranBuilding building = GetBuilding(bo.State as TerranState);
			if (building != null)
				building.Built();
		}
		public virtual void OnProductionStart(IBuildOrder bo)
		{
			TerranState.TerranBuilding building = GetBuilding(bo.State as TerranState);
			if (building != null)
				building.Building++;
		}
	}
}
